package cn.ayanami.blog.article.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.ayanami.blog.article.entity.dao.CategoryDao;
import cn.ayanami.blog.article.entity.dto.AddCategoryDto;
import cn.ayanami.blog.article.entity.dto.EditCategoryDto;
import cn.ayanami.blog.article.entity.po.CategoryPo;
import cn.ayanami.blog.article.entity.vo.CategoryVo;
import cn.ayanami.blog.article.service.CategoryService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public Mono<Integer> addCategory(AddCategoryDto dto) {
        var category = new CategoryPo();
        BeanUtils.copyProperties(dto, category);
        categoryDao.save(category).subscribe();
        return Mono.just(Integer.valueOf(1));
    }

    @Override
    public Mono<Integer> editCategoryDto(EditCategoryDto dto) {
        var category = categoryDao.findById(dto.getCategoryId());

        return category.mapNotNull(po -> {
            BeanUtils.copyProperties(dto, po);
            categoryDao.save(po);
            return Integer.valueOf(1);
        }).defaultIfEmpty(-1);
    }

    @Override
    public Flux<CategoryVo> getAllCategories() {

        return categoryDao.findAll().map(po -> {
            CategoryVo vo = new CategoryVo();
            BeanUtils.copyProperties(po, vo);
            return vo;
        });
    }

    @Override
    public Mono<Integer> deleteCategory(Integer categoryId) {

        return categoryDao.existsById(categoryId).map(result -> {
            if (result.booleanValue()) {
                return Integer.valueOf(1);
            } else {
                return Integer.valueOf(-1);
            }
        });
    }

}
